package service;

import java.util.Collection;
import java.util.Date;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import common.IPersistenceManager;
import entity.Account;
import entity.Equipment;
import entity.EquipmentBorrow;
import entity.EquipmentLogin;
import entity.EquipmentReturn;
import entity.EquipmentScrap;
import entity.Event;
import entity.Staff;
import entity.Equipment.STATE;

@Service
@Transactional
public class EquipmentService implements IEquipmentService {

	@Autowired
	IPersistenceManager persistenceManager;

	@Override
	public void login(Equipment equipment) {

		if (equipment != null
				&& equipment.getState().equals(STATE.EQUIPMENTNEW)) {
			Event event = new EquipmentLogin(equipment);
			persistenceManager.save(event);
		}
	}

	@Override
	public void borrow(Staff staff, Equipment equipment) {
		if (staff == null || equipment == null) {
			return;
		}
		if (equipment.getState().equals(STATE.EQUIPMENTINSTORE)) {
			equipment.setAccount(staff);
			staff.getEquipments().add(equipment);
			Event event = new EquipmentBorrow(staff, equipment);
			persistenceManager.save(staff);
			persistenceManager.save(event);
		}
	}

	@Override
	public void returnEquipment(Staff staff, Equipment equipment) {
		if (equipment.getState().equals(STATE.EQUIPMENTBORROWED)
				&& equipment.getAccount().equals(staff)) {
			equipment.setAccount(staff.getCompany());
			staff.getEquipments().remove(equipment);
			Event event = new EquipmentReturn(staff, equipment);
			persistenceManager.save(staff);
			persistenceManager.save(event);
		}
	}

	@Override
	public void bad(Equipment equipment) {
		Event event = new EquipmentScrap(equipment);
		persistenceManager.save(event);
	}

	@Override
	public Account getAccount(Equipment equipment) {
		return equipment.getAccount();
	}

	@Override
	public void printEventLog(Equipment equipment) {
		Collection<Event> events = equipment.getEvents();

		for (Event event : events) {
			System.out.println(event.getId());
		}

	}

	@Override
	public String getEquipmentState(Equipment equipment) {
		equipment = persistenceManager.get(Equipment.class, equipment.getId());

		String stateString;

		switch (equipment.getState()) {
		case EQUIPMENTINSTORE:
			stateString = "INSTORE";
			break;
		case EQUIPMENTNEW:
			stateString = "NEW";

			break;
		case EQUIPMENTBORROWED:
			stateString = "BORROWED";

			break;
		case EQUIPMENTBAD:
			stateString = "BAD";

			break;
		default:
			stateString = "";
			break;
		}

		return stateString;
	}

	@Override
	public Collection<Event> getEventLog(Equipment equipment) {
		equipment = persistenceManager.get(Equipment.class, equipment.getId());
		return equipment.getEvents();
	}

}
